/*
 * SendingRequests: sending HTTP requests in GET or POST mode
 */
/* File history:
 *  1.00.000 -- 2009/09/18 (PL) -- Creation.
 */
/*
Author: Philippe Lhoste <PhiLho(a)GMX.net> http://Phi.Lho.free.fr
Copyright notice: For details, see the following file:
http://Phi.Lho.free.fr/softwares/PhiLhoSoft/PhiLhoSoftLicence.txt
This program is distributed under the zlib/libpng license.
Copyright (c) 2009 Philippe Lhoste / PhiLhoSoft
 */

 package Logger;

import javafx.data.Pair;
import javafx.io.http.*; // HttpHeader, HttpRequest, HttpStatus, URLConverter
import java.io.*;

public class LogSender {

    public function SendRequest(information: Pair[], method: String): Void {
        if (information == null or sizeof information == 0)
            return;

        var urlConverter = URLConverter {};

        // Hard-code the location, in general we rarely change for a given program...
        var location = "http://kraynel.free.fr/LogRequest.php";
        if (method == HttpRequest.GET) {
            var params = urlConverter.encodeParameters(information);
            location = "{location}?{params}";
        }

        var httpHeaders: HttpHeader[] = HttpHeader {
                    name: HttpHeader.USER_AGENT;
                    value: "JavaFX Client";
                }

        var httpRequest: HttpRequest = HttpRequest {
                    location: location
                    headers: httpHeaders
                    method: method

                    onStarted: function(): Void {
                        println("onStarted - started performing method: {httpRequest.method} on location: {httpRequest.location}");
                    }

                    onOutput: function(os: java.io.OutputStream): Void {
                        println("onOutput");
                        try {
                            var encodedMessage = urlConverter.encodeParameters(information);
                            os.write(encodedMessage.getBytes());
                        } finally {
                            os.close();
                        }
                    }

                    // Reading server's answer
                    onInput: function(is: java.io.InputStream): Void {
                        var reader: BufferedReader;
                        try {
                            println("onInput - bytes of content available: {is.available()}");
                            // For example:
                            //				pullParser.input = is;
                            //				pullParser.parse();
                            // or:
                            var buffer = new java.lang.StringBuilder();
                            reader = new BufferedReader(new InputStreamReader(is));
                            var line: String;
                            while ((line = reader.readLine()) != null) {
                                buffer.append(line).append('\n');
                            }
                            println("--- Content:\n{buffer.toString()}---");
                        } finally {
                            is.close();
                            reader.close();
                        }
                    }

                    onConnecting: function(): Void {
                        println("onConnecting");
                    }
                    onDoneConnect: function(): Void {
                        println("onDoneConnect");
                    }

                    // Section skipped if GET request
                    onWriting: function(): Void {
                        println("onWriting");
                    }
                    // Here call onOutput if doing POST request
                    onToWrite: function(bytes: Long): Void {
                        println("onToWrite - entire content to be written: {bytes} bytes");
                    }
                    onWritten: function(bytes: Long): Void {
                        println("onWritten - {bytes} bytes has now been written");
                    }
                    onDoneWrite: function(): Void {
                        println("doneWrite");
                    }

                    onReadingHeaders: function(): Void {
                        println("onReadingHeaders");
                    }
                    onResponseCode: function(code: Integer): Void {
                        println("onResponseCode - responseCode: {code}");
                        if (code != 200) {
                            println("  ERROR");
                        }
                    }
                    onResponseMessage: function(msg: String): Void {
                        println("onResponseMessage - responseMessage: {msg}");
                    }
                    onResponseHeaders: function(headerNames: String[]): Void {
                        println("onResponseHeaders - there are {sizeof headerNames} response headers:");
                        for (name in headerNames) {
                            println(" - {name}: {httpRequest.getResponseHeaderValue(name)}");
                        }
                    }
                    onReading: function(): Void {
                        println("onReading");
                    }
                    onToRead: function(bytes: Long): Void {
                        if (bytes < 0) {
                            println("onToRead - Content length not specified by server; bytes: {bytes}");
                        } else {
                            println("onToRead - total number of content bytes to read: {bytes}");
                        }
                    }
                    onRead: function(bytes: Long): Void {
                        // The toread variable is non negative only if the server provides the content length
                        def progress = if (httpRequest.toread > 0) "({(bytes * 100 / httpRequest.toread)}%)" else "";
                        println("onRead - bytes read: {bytes} {progress}");
                    }
                    // Then we have onInput

                    onDoneRead: function(): Void {
                        println("onDoneRead");
                    }
                    // Usually we do the update GUI stuff here
                    onDone: function(): Void {
                        println("onDone");
                    }

                    onException: function(ex: java.lang.Exception): Void {
                        println("onException - exception: {ex.getClass()} {ex.getMessage()}");
                        ex.printStackTrace();
                    }
                }
        httpRequest.start();
    }

}
